<template>
  <div class="index" v-if="this.gmRecharge">
    <top-bar :title="'充值K金'"/>
    <div class="maincontainer">
      <div class="pay_main">
        <p class="recharge">选择充值金额</p>
        <div class="minVideoViewBox">
          <ul class="pay_mini">
            <li class="miniStreamView" v-for="(item, key) in this.gmRecharge.pay_button">
              <div class="recommend" v-if="item.recommend">
                <img src="../../assets/images/tuijian.png" alt="">
                <span>推荐</span>
              </div>
              <a href="javascript:;" :class="{'clickmoney': active === key}" @click="changeAmount(key)">
                <p class="describe">{{ item.gm_cnt }}K金</p>
                <p class="money"><span>￥</span>{{ item.amount }}</p></a>
            </li>
          </ul>
        </div>
        <div class="custom">
          <input type="number" v-model='otherAmount' placeholder="自定义充值金额"
                 style="font-size: 0.33rem;text-align: center;font-weight: 700;"
                 @input="otherAmountChange()"></input>
        </div>
        <div class="pay_way">
          <p class="paytype">选择支付方式</p>
          <div class="payment" v-if="this.gmRecharge">
            <li v-for="(item, key) in this.gmRecharge.pay_type">
              <div class="zf">
                <a :class="{'activetype': item.payway === payway}" @click="activeChange(key)">
                  <img class="img" :src=item.icon alt="">
                  <p>{{ item.name }}</p>
                </a>
              </div>
            </li>
          </div>
        </div>
      </div>
      <div class="discount">
        <div class="coupon" @click="chooseCoupon">
          <p>选择优惠券</p>
          <div class="quan">
            <div v-if="coupon">{{ coupon.title }}</div>
            <div v-else-if="this.gmRecharge.coupon_list.list.length" style="color: red">请选择优惠券</div>
            <div v-else style="color: gray;">无</div>
            <div style="display:flex;">
              <div style="color:#ff0300;font-size:0.3rem;font-weight: 700;" v-if="coupon">-{{ coupon.money }}元</div>
              <i class="el-icon-arrow-right" style="font-size: 0.35rem;line-height: 1.1rem;"></i>
            </div>
          </div>
        </div>
      </div>
      <div class="pay_gray">
        <div class="pay_btn">
          <button class="bottomgradual" @click="paypost">确认支付(￥{{ real_amount }})</button>
        </div>
      </div>
    </div>
    <el-dialog
      :modal-append-to-body='false'
      :visible.sync="showCoupon"
      :showClose="false"
      :close-on-press-escape="false"
      v-if="this.gmRecharge"
      width="9.2rem"
      :top="coupon_top"
      center
    >
      <span slot="title" style="font-size: 0.34rem;height: 0.24rem">优惠券</span>
      <div style="max-height: 6rem;overflow-x: hidden;overflow-y: auto">
        <li class="coupon_li" v-for="(item, key) in this.gmRecharge.coupon_list.list" :key="key" :label="item.id"
            @click="changeCoupon(key)">
          <img v-if="item.id!=coupon_id" src="@/assets/images/unselected.png" class="coupon_icon">
          <img v-else src="@/assets/images/selected.png" class="coupon_icon">
          <div class="coupon_info">
            <div class="left">
              <div class="coupon_money">
                <span>¥</span>
                <span :class="fontSize(item.money)">{{ item.money }}</span>
              </div>
              <div class="coupon_name">
                K金优惠券
              </div>
            </div>
            <div class="center">
              <span>{{ item.title }}</span>
              <span>截止时间：{{ dateTransform(item.end_time, 'yyyy-MM-dd') }}</span>
              <span>{{ item.overlay_type == 0 ? '可与游戏内折扣叠加使用' : '不可与游戏内折扣叠加使用' }}</span>
            </div>
          </div>
        </li>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="qrcodeVisible"
      width="240px"
      :append-to-body='true'
      center
    >
      <span slot="title" style="font-size: 20px;height: 30px">{{ qrcodeTitle }}</span>
      <div id="qrcode"></div>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import topBar from './topBar'
import * as api from '../../api'
import QRCode from 'qrcodejs2' // 引入qrcode;

export default {
  components: {
    topBar
  },
  data () {
    return {
      active: 0,
      otherAmount: '',
      showCoupon: false,
      type: 0,
      payway: '',
      coupon_id: 0,
      coupon: null,
      gmRecharge: null,
      // 扫码支付
      qrcodePayRes: '',
      qrcodeVisible: false,
      qrcodeTimer: 0,
      qrcodeTitle: '',
    }
  },
  computed: {
    amount () {
      if (this.otherAmount) {
        return this.otherAmount
      }
      if (!this.gmRecharge) {
        return 0
      }
      if (this.active < 0) {
        return 0
      }
      let item = this.gmRecharge.pay_button[this.active]
      return item.gm_cnt
    },
    real_amount () {
      let amount = this.amount
      if (this.coupon) {
        amount = amount - this.coupon.money
      }
      if (!this.coupon || !this.coupon.overlay_type) {//优惠券与折扣不可叠加
        amount *= this.gmRecharge.gm_rate
      }
      return (amount).toFixed(2)
    },
    gmPayPost () {
      return this.$store.state.gmPayPost
    },
    list () {
      return this.gmRecharge.pay_type.filter((type, i) => {
        type.id = i
        return type
      })
    },
    coupon_top () {
      return 'calc(50vh - 3rem)'
    },
    ...mapGetters([
      'baseInfo',
      'failMsg'
    ])
  },
  watch: {
    gmPayPost () {
      if (this.gmPayPost.status === 2) {
        this.Toast('支付成功', 500)
        api.gmRecharge(data => {
          this.gmRecharge = data
          this.autoSelectCoupon()
        }, msg => {
        })
        return
      }
      let ua = window.navigator.userAgent.toLowerCase()
      if (ua.match(/micromessenger/i) === 'micromessenger') {
        window.parent.postMessage(JSON.stringify({
          type: 'weixin.href',
          value: this.gmPayPost.order_id
        }), '*')
        return
      }
      switch (this.gmPayPost.pay_type) {
        case 'alipayh5':
        case 'alipayxy':
        case 'alipayqr':
          let doc = document
          if (!window.huo) {
            doc = window.parent.document
          }
          let frag = doc.createDocumentFragment()
          let div = doc.createElement('div')
          div.innerHTML = this.gmPayPost.btoken ? this.gmPayPost.btoken : this.gmPayPost.token
          frag.appendChild(div)
          doc.querySelector('body').appendChild(frag.firstChild)
          let alipay = doc.querySelector('#alipaysubmit')
          alipay.submit()
          break
        case 'wxpayh5':
          if (!window.huo) {
            window.top.location.href = this.gmPayPost.token
          } else {
            window.location.href = this.gmPayPost.token
          }
          break
        case 'wxpayqr':
        case 'alipayqrcode':
          if (this.gmPayPost.pay_type === 'wxpayqr') {
            this.qrcodeTitle = '微信支付'
          } else {
            this.qrcodeTitle = '支付宝支付'
          }
          this.qrcodePayRes = this.gmPayPost.token
          this.qrcodeVisible = true
          let queryNum = 0
          this.$nextTick(() => {
            this.getQrocde()
          })
          if (this.qrcodeTimer) {
            clearInterval(this.qrcodeTimer)
          }
          this.qrcodeTimer = setInterval(() => {
            if (!this.qrcodeVisible) {
              clearInterval(this.qrcodeTimer)
              return
            }
            queryNum++
            if (queryNum >= 20) {
              this.qrcodeVisible = false
              clearInterval(this.qrcodeTimer)
              this.Toast('失败原因：支付超时', 500)
              return
            }
            let post = {
              'order-order_id': this.gmPayPost.order_id
            }
            api.gmPayQuery(post, res => {
              if (res.status === 1) {
              } else if (res.status === 2) {
                this.qrcodeVisible = false
                clearInterval(this.qrcodeTimer)
                this.Toast('支付成功', 500)
                this.close(true)
              } else if (res.status === 3) {
                clearInterval(this.qrcodeTimer)
                this.Toast('支付失败', 500)
              }
            }, fail => {
              clearInterval(this.qrcodeTimer)
              this.Toast(fail, 500)
            })
          }, 3000)
          break
        default:
          if (!window.huo) {
            window.top.location.href = this.gmPayPost.token
          } else {
            window.location.href = this.gmPayPost.token
          }
          break
      }
    },
    failMsg () {
      this.failMsg && this.Toast(this.failMsg, 500)
    },
    coupon_id () {
      if (this.coupon_id === 0) {
        this.coupon = null
        return
      }
      let coupon = this.gmRecharge.coupon_list.list.filter(item => item.id === this.coupon_id)[0]
      if (coupon) {
        if (coupon.condition > this.amount) {
          this.coupon_id = 0
          this.Toast('未满足使用条件，换一张代金券试试吧', 500)
        } else {
          this.coupon = coupon
        }
      } else {
        this.coupon_id = 0
      }
    },
  },
  methods: {
    fontSize (item) {
      console.log(item)
      if (item < 1000) {
        return 'font_size_1'
      }
      if (item < 10000) {
        return 'font_size_2'
      }
      return 'font_size_3'
    },
    changeCoupon (key) {
      if (this.coupon_id == this.gmRecharge.coupon_list.list[key].id) {
        this.coupon_id = null
      } else {
        this.coupon_id = this.gmRecharge.coupon_list.list[key].id
      }
      this.showCoupon = false
    },
    chooseCoupon () {
      if (!this.gmRecharge.coupon_list.list.length) {
        return this.Toast('无可用优惠券', 500)
      }
      this.showCoupon = true
    },
    otherAmountChange () {
      this.active = -1
      let val = parseInt(this.otherAmount)
      if (val < 0) {
        this.otherAmount = 0
      } else {
        this.otherAmount = val
      }
      this.autoSelectCoupon()
    },
    changeAmount (active) {
      this.active = active
      this.otherAmount = ''
      this.autoSelectCoupon()
    },
    activeChange (val) {
      this.payway = this.gmRecharge.pay_type[val].payway
    },
    inputAmount () {
      if (isNaN(this.otherAmount)) {
        this.otherAmount = this.otherAmount.substring(0, this.otherAmount.length - 1)
      }
      if (!isNaN(this.otherAmount)) {
        this.amount = this.otherAmount
      }
      this.active = 6
    },
    paypost () {
      if (this.amount <= 0) {
        return this.Toast('充值金额必须大于0', 500)
      }
      if (!this.payway) {
        return this.Toast('请选择支付方式', 500)
      }
      let postData = {
        payway: this.payway,
        amount: this.amount,
        coupon_id: this.coupon_id
      }
      if (!window.huo) {
        let appId = localStorage.getItem('appId')
        postData.back_url = window.apiUrl + '/game/' + appId
      }
      this.$store.dispatch('gmPayPost', postData)
    },
    autoSelectCoupon () {
      if (!this.gmRecharge.coupon_list || this.gmRecharge.coupon_list.count == 0) {
        this.coupon_id = 0
        return
      }
      let max = 0
      this.coupon_id = null
      this.gmRecharge.coupon_list.list.filter(
        item => {
          if (item.condition <= this.amount && (!item.overlay_type || this.gmRecharge.gm_rate >= 1)) {
            if (max < item.money) {
              max = item.money
              this.coupon_id = item.id
            }
            return true
          }
          return false
        }
      )
    },
    getQrocde () {
      document.getElementById('qrcode').innerHTML = ''
      this.$nextTick(function () {
        //生成二维码
        this.qrcode()
      })
    },
    qrcode () {
      new QRCode('qrcode', {
        width: 200,
        height: 200, // 高度
        text: this.qrcodePayRes // 二维码内容
      })
    },
  },
  created () {
    api.gmRecharge(data => {
      this.gmRecharge = data
      this.autoSelectCoupon()
    }, msg => {
      msg && this.Toast(msg, 500)
      this.$router.push({path: '/me/index'})
    })
  }
}
</script>

<style lang="scss" scoped>
.coupon_li {
  display: flex;
}

.coupon_icon {
  width: 40px;
  height: 40px;
  margin-top: 0.84rem;
  margin-right: 0.3rem;
}

.coupon_info {
  display: flex;
  align-items: center;
  padding: 0 0.4rem 0 0.38rem;
  margin-bottom: 0.3rem;
  width: 100%;
  height: 2.24rem;
  background: url("../../assets/images/coupon.png") no-repeat;
  background-size: 100% 100%;

  .left {
    display: flex;
    flex-direction: column;
    justify-content: center;
    margin-left: 0.1rem;
    width: 1.6rem;

    .coupon_money {
      display: flex;
      align-items: baseline;
      justify-content: center;

      > span:nth-child(1) {
        font-family: SourceHanSansCN-Heavy, SourceHanSansCN;
        font-weight: 800;
        color: #FF5832;
      }

      > span:nth-child(2) {
        margin-left: 0.05rem;
        font-family: SourceHanSansCN-Bold, SourceHanSansCN;
        font-weight: bold;
        color: #FF5832;
      }
    }

    .coupon_name {
      display: flex;
      width: 100%;
      justify-content: center;
      font-size: 0.24rem;
      font-family: SourceHanSansCN-Regular, SourceHanSansCN;
      font-weight: 400;
      color: #FF5832;
      margin-top: 0.29rem;
    }
  }

  .center {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 0.9rem;
    margin-top: 0.1rem;

    > span:nth-child(1) {
      font-size: 0.35rem;
      font-family: SourceHanSansCN-Bold, SourceHanSansCN;
      font-weight: bold;
      color: #181818;
    }

    > span:nth-child(2) {
      font-size: 0.27rem;
      font-family: SourceHanSansCN-Regular, SourceHanSansCN;
      font-weight: 400;
      color: #666666;
      margin: 0.24rem 0;
    }

    > span:nth-child(3) {
      font-size: 0.29rem;
      font-family: SourceHanSansCN-Regular, SourceHanSansCN;
      font-weight: 400;
      color: #666666;
    }
  }
}

/deep/ .el-dialog__header {
  padding: 0;
}

.index {
  padding: 0.75rem 0;

  /deep/ .title {
    padding: 0 0.48rem;
    margin-bottom: 0.48rem;
  }

  .maincontainer {
    height: 8.5rem;
    overflow: scroll;
    opacity: 0.9;
    position: inherit;
    padding-top: 0;
  }

  .pay {
    &_main {
      padding: 0 30px;
    }

    &_cnt {
      border-bottom: 1px solid #DEDEDE;
      color: #333;
      font-size: 26px;
      height: 90px;
      line-height: 90px;

      > span {
        color: #FF8C41;
      }
    }

    &_way {
      border-bottom: 1px solid #DEDEDE;
      font-size: 26px;
      height: 90px;
      line-height: 90px;

      > span {
        background-image: url(../../assets/images/uc_xiala.png);
        background-position: right center;
        background-repeat: no-repeat;
        background-size: 30px 30px;
        color: #FF8C41;
        float: right;
        line-height: 90px;
        padding-right: 50px;
      }
    }

    &_amount {
      border-top: 1px solid #DEDEDE;
      color: #333;
      font-size: 26px;
      height: 80px;
      line-height: 80px;

      > span {
        color: #42B35C;
      }
    }

    &_items {
      margin: 0 -15px;
      overflow: hidden;
      padding-bottom: 25px;

      > li {
        float: left;
        margin-top: 25px;
        padding: 0 15px;
        width: 33.33%;

        > a {
          border: 2px solid #DEDEDE;
          border-radius: 3px;
          color: #393939;
          display: block;
          font-size: 26px;
          line-height: 80px;
          text-align: center;
        }

        > input {
          border: 2px solid #DEDEDE;
          border-radius: 3px;
          display: block;
          line-height: 80px;
          text-align: center;
          width: 100%;
        }

        .active {
          background-image: url(../../assets/images/uc_checked.png);
          background-position: right bottom;
          background-repeat: no-repeat;
          background-size: 48px 48px;
          border-color: #42B35C;
          color: #42B35C;
          z-index: 999;
        }
      }
    }

    &_gray {
      background-color: #E9ECF1;
      padding-top: 16px;
    }

    &_btn {
      background-color: #fff;
      padding: 30px;

      > button {
        background-color: #FF8C41;
        border-radius: 8px;
        color: #fff;
        display: block;
        font-size: 30px;
        line-height: 80px;
        width: 100%;
      }
    }
  }

  .recommend {
    position: relative;

    img {
      width: 1.2rem;
      height: 0.58rem;
      position: absolute;
    }

    span {
      position: absolute;
      color: #fff;
      display: inline-block;
      text-align: center;
      font-size: 0.3rem;
      width: 50%;
      padding-top: 0.15rem;
    }
  }

  .recharge {
    font-size: 0.4rem;
    font-weight: 600;
    margin: 0px 0px 0.2rem 0px;
  }

  .pay_main {
    margin-top: 0.2rem;
  }

  .describe {
    font-size: 0.35rem;
    color: #333333;
    font-weight: 600;
    text-align: center;
    padding: 0.65rem 0rem 0.2rem 0rem;
  }

  .money {
    font-size: 0.45rem;
    color: #FF0300;
    font-weight: 600;
    text-align: center;

    span {
      font-size: 0.32rem;
    }
  }

  .pay_mini {
    font-size: 0.25rem;
  }

  .pay_gray {
    padding: 0;
  }

  .pay_btn {
    background-color: #f4f4f4;
    padding: 0.3rem;
  }

  .pay_btn .bottomgradual {
    background-image: linear-gradient(to right, #FF0000, #FFD500);
    border-radius: 1.2rem;
  }

  .discount {
    height: 1.3rem;
    line-height: 0.8rem;

    .coupon {
      height: 1.3rem;
      line-height: 0.8rem;
      display: flex;
      justify-content: space-between;

      p {
        font-size: 0.4rem;
        line-height: 1.2rem;
        font-weight: 600;
        padding-left: 0.5rem;
        color: #363739;
      }

      .quan {
        width: 65%;
        height: 1.1rem;
        display: flex;
        font-size: 0.4rem;
        background-color: #fff;
        border-radius: 10px;
        margin-top: 5px;
        display: flex;
        justify-content: space-between;
        margin-right: 30px;
        padding-left: 20px;
        padding-right: 10px;

        div {
          line-height: 1.1rem;
          font-size: 0.35rem;
        }
      }
    }
  }

  .pay_way {
    height: 3rem;
    border: none;

    .paytype {
      color: #181818;
      font-weight: 600;
      padding-bottom: 0.25rem;
      font-size: 0.4rem;
    }

    .payment {
      display: flex;
      border-bottom: none;

      li {
        width: 2.3rem;
        height: 2rem;
        border-radius: 7px;
        margin-right: 28px;

        .zf {
          width: 2.3rem;
          height: 2rem;
          border-radius: 0.08rem;
          margin-right: 28px;

          p {
            text-align: center;
            font-size: 0.35rem;
          }

          .img {
            width: 1rem;
            height: 0.95rem;
            margin: 0.2rem 0.65rem;
          }

          background-color: #FFF;
          box-sizing: border-box;
        }
      }
    }
  }

  .custom {
    width: 100%;
    height: 0.9rem;
    border-radius: 0.15rem;
    background-color: #fff;
    opacity: 0.9;
    font-size: 0.35rem;
    color: #FF7373;
    text-align: center;
    line-height: 0.9rem;
    margin-bottom: 0.25rem;
  }

  .activetype {
    display: inline-block;
    height: 2rem;
    border-radius: 8px;
    border: 1px solid #F3481C;
    background-color: #fff;
    box-shadow: 0px 2px 7px 0px rgba(85, 110, 97, 0.35);
    border-radius: 7px;
    background-image: url(../../assets/images/checked2.png);
    background-position: right bottom;
    background-repeat: no-repeat;
    background-size: 48px 48px;
  }

  .minVideoViewBox {
    width: 100%;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;

    &::-webkit-scrollbar {
      // 滚动条整体
      background: none;
    }
  }

  .miniStreamView {
    width: 2.3rem;
    height: 2rem;
    display: inline-block;
    background: #FFFFFF;
    opacity: 0.9;
    margin: 6px;
    border-radius: 0.1rem;

    a {
      width: 100%;
      height: 100%;
      display: inline-block;
    }
  }

  .clickmoney {
    background-image: url(../../assets/images/checked2.png);
    background-position: right bottom;
    background-repeat: no-repeat;
    background-size: 48px 48px;
    border: 1px solid #F3481C !important;
    z-index: 99999;
    border-radius: 0.1rem;
  }

  .font_size_1 {
    font-size: 0.64rem;
  }

  .font_size_2 {
    font-size: 0.54rem;
  }

  .font_size_3 {
    font-size: 0.44rem;
  }
}
</style>
